package com.ks.common.aspect;

import com.ks.common.annotation.Permission;
import com.ks.common.interceptor.LoginInterceptor;
import com.ks.common.model.UserRoles;
import com.ks.common.util.JsonData;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

/**
 * 许可切面
 *
 * @author KingAusten
 * @date 2022/08/17 17:50:28
 */
@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class PermissionAspect{

    private final RedissonClient redissonClient;

    @Pointcut("@annotation(com.ks.common.annotation.Permission)")
    public void permission(){

    }

    @Around("permission()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{

        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        String role = signature.getMethod()
                .getAnnotation(Permission.class)
                .role();
        log.info("角色：{}",role);

        long accountNo = LoginInterceptor.threadLocal.get()
                .getAccountNo();
        log.info("账号：{}",accountNo);

        UserRoles userToRole = (UserRoles)redissonClient.getMap("userToRole")
                .get(accountNo);
        log.info("用户角色权限：{}",userToRole);

        if(userToRole.getPermissions()
                .contains(role)){
            return joinPoint.proceed();
        }else{
            return JsonData.buildError("没有权限");
        }
    }

}
